package com.gsmr.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.gsmr.entity.Group;
import com.gsmr.entity.PageBean;
import com.gsmr.entity.User;
import com.gsmr.realm.MultipleDataSource;
import com.gsmr.service.GroupService;
import com.gsmr.service.MemberShipService;
import com.gsmr.service.UserService;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.Md5Util;
import com.gsmr.util.PropertityUtil;
import com.gsmr.util.ResponseUtil;
import com.gsmr.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author 作者 : 黄志新
 * @version 创建时间：2017年8月11日 上午12:13:57 类说明：用户Controller层
 */
@CrossOrigin
@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;

	@Resource
	private MemberShipService memberShipService;

	@Resource
	private GroupService groupService;

	/**
	 * 用户登录
	 */
	@RequestMapping("/login")
	public void login(HttpServletRequest requset, HttpServletResponse response) throws Exception {
		String userName = requset.getParameter("userName");
		String password = requset.getParameter("password");
		
		Map<String, Object>map = new HashMap<>();
		map.put("userId", userName);
		
		String groupId =  memberShipService.getGroupId(map);
		String database = requset.getParameter("database");
		requset.getSession().setAttribute("groupIdForAuth", groupId);
		System.out.println("用户登录: " + database);
		MultipleDataSource.currentDataSource = database;

		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userName, Md5Util.md5(password, Md5Util.SALT));
		JSONObject result = new JSONObject();

		try {
			// subject拿token到MyRealm类的doGetAuthenticationInfo方法校验用户名和密码，若返回的Manager对象为空，则设置返回的AuthenticationInfo对象为空，然后则报错
			subject.login(token);
			result.put("success", true);

		} catch (Exception e) {
			result.put("success", false);
			result.put("errorInfo", "用户名或密码错误！");
			e.printStackTrace();
		}
		ResponseUtil.write(response, result);	
	}

	/**
	 * 分页条件查询用户
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows, User s_user, HttpServletResponse response)
			throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", StringUtil.formatLike(s_user.getId())); // 查询用户名获取
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<User> userList = userService.find(map);
		Long total = userService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(userList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		
	}

	/**
	 * 分页条件查询用户以及用户所有的角色
	 */
	@RequestMapping("/listWithGroups")
	public void listWithGroups(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows, User s_user, HttpServletResponse response)
			throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", StringUtil.formatLike(s_user.getId()));
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<User> userList = userService.find(map);
		for (User user : userList) {
			StringBuffer groups = new StringBuffer();
			List<Group> groupList = groupService.findByUserId(user.getId());
			for (Group g : groupList) {
				groups.append(g.getName() + ",");
			}
			if (groups.length() > 0) {
				user.setGroups(groups.deleteCharAt(groups.length() - 1).toString()); // 去掉最后一个逗号
			} else {
				user.setGroups(groups.toString());
			}
		}
		Long total = userService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(userList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		
	}

	/**
	 * 添加或者修用户
	 */
	@RequestMapping("/save")
	public void save(User user, HttpServletResponse response, Integer flag) throws Exception {
		int resultTotal = 0; // 操作的记录条数
		if (flag == 1) {
			user.setPassword(Md5Util.md5(user.getPassword(), Md5Util.SALT));
			resultTotal = userService.add(user);
		} else {
			resultTotal = userService.update(user);
		}
		JSONObject result = new JSONObject();
		if (resultTotal > 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		
	}

	/**
	 * 删除用户
	 */
	@RequestMapping("/delete")
	public void delete(@RequestParam(value = "ids") String ids, HttpServletResponse response) throws Exception {
		String[] idsStr = ids.split(",");
		for (int i = 0; i < idsStr.length; i++) {
			userService.delete(idsStr[i]);
		}
		JSONObject result = new JSONObject();
		result.put("success", true);
		ResponseUtil.write(response, result);
		
	}

	/**
	 * 判断是否存在指定用户名
	 */
	@RequestMapping("/existUserName")
	public void existUserName(String userName, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		if (userService.findById(userName) == null) {
			result.put("exist", false);
		} else {
			result.put("exist", true);
		}
		ResponseUtil.write(response, result);
		
	}

	/**
	 * 修改用户密码
	 */
	@RequestMapping("/modifyPassword")
	public void modifyPassword(String id, String password, String oldPassword, String newPassword,
			HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		User user = new User();
		user.setId(id);
		if (password.equals(Md5Util.md5(oldPassword, Md5Util.SALT))) {
			user.setPassword(Md5Util.md5(newPassword, Md5Util.SALT));
			int resultTotal = userService.update(user);
			if (resultTotal > 0) {
				result.put("success", true);
			} else {
				result.put("success", false);
			}
		} else {
			result.put("success", false);
			result.put("msg", "用户原密码输入错误！");
		}

		ResponseUtil.write(response, result);
		
	}

	/**
	 * 用户注销
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) throws Exception {
		// 由Shrio控制，则由Shrio操作清除session并退出。
		// 若是session.invalidate()，则会报错，因为此时Shrio失效，redirect则跳转不了。
		
		MultipleDataSource.clearCustomerType();
		MultipleDataSource.currentDataSource = MultipleDataSource.dataSource1;
		// 切换数据源
		
		MultipleDataSource.setCustomerType(MultipleDataSource.currentDataSource);
		SecurityUtils.getSubject().logout();
		return "redirect:/login.jsp";
	}

	/**
	 * 导出用户
	 */
	@RequestMapping("/export")
	public void export(@RequestParam(value = "ids") String ids, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Workbook wb = new HSSFWorkbook();
		String headers[] = { "用户名", "密码", "姓", "名", "Email" };
		if (ids != null && !ids.equals("null") && !ids.equals("")) {
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("ids", idsList);
			List<User> userList = userService.findByIds(map);
			try {
				ExcelUtil.fillExcelData_User(userList, wb, headers);
				ResponseUtil.export(response, wb, "导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			map.put("ids", null);
			List<User> userList = userService.findByIds(map);
			try {
				ExcelUtil.fillExcelData_User(userList, wb, headers);
				ResponseUtil.export(response, wb, "导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * 用模板导出用户
	 */
	@RequestMapping("/exportByTemplate")
	public void exportByTemplate(@RequestParam(value = "ids") String ids, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		if (ids != null && !ids.equals("null") && !ids.equals("")) {
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("ids", idsList);
			List<User> userList = userService.findByIds(map);
			try {
				Workbook wb = ExcelUtil.fillExcelDataWithTemplate_User(userList, "userExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			map.put("ids", null);
			List<User> userList = userService.findByIds(map);
			try {
				Workbook wb = ExcelUtil.fillExcelDataWithTemplate_User(userList, "userExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * 用户上传
	 */
	@RequestMapping("/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					String path = PropertityUtil.UPLOAD_PATH + FormatDate.formatDate() + file.getOriginalFilename();
					// 上传
					File newFile = new File(path);
					file.transferTo(newFile);
					// 写数据进数据库
					POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(newFile));
					HSSFWorkbook wb = new HSSFWorkbook(fs);
					HSSFSheet hssfSheet = wb.getSheetAt(0); // 获取第一个Sheet页
					JSONObject result = new JSONObject();
					try {
						if (hssfSheet != null) {
							for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
								HSSFRow hssfRow = hssfSheet.getRow(rowNum);
								if (hssfRow == null) {
									continue;
								}
								User user = new User();
								user.setId(ExcelUtil.formatCell(hssfRow.getCell(0)));
								user.setPassword(Md5Util.md5(ExcelUtil.formatCell(hssfRow.getCell(1)), Md5Util.SALT));
								user.setFirstName(ExcelUtil.formatCell(hssfRow.getCell(2)));
								user.setLastName(ExcelUtil.formatCell(hssfRow.getCell(3)));
								user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(4)));
								userService.add(user);
							}
						}
						result.put("success", "true");
					} catch (Exception e) {
						result.put("success", "false");
						e.printStackTrace();
					}
					ResponseUtil.write(response, result);
				}
			}
		}
		
	}

	@RequestMapping(value = "/chart")
	public void chart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// {"list":[{"name":"一号","age":19},{"name":"二号","age":22},{"name":"test","age":19}....]}
		// [{"email":"123@qq.com","firstName":"班","groups":"","id":"bz","lastName":"长","password":"111"},{"email":"123@qq.com","firstName":"班","groups":"","id":"bzr","lastName":"主任","password":"111"},{"email":"sds@qq.com","firstName":"王","groups":"","id":"cc2","lastName":"二小","password":"111"},{"email":"123@qq.com","firstName":"杜","groups":"","id":"dzt","lastName":"子腾","password":"111"},{"email":"1097294385@qq.com","firstName":"黄","groups":"","id":"gsmr","lastName":"志新","password":"e3ef48d9b4173749ec51b9fee8d499a6"},{"email":"1234567@qq.com","firstName":"陈","groups":"","id":"jl","lastName":"铰链时","password":"a9367a02216c7a00af6a4d33632bf147"},{"email":"123@qq.com","firstName":"李","groups":"","id":"lisi","lastName":"四","password":"111"},{"email":"123@qq.com","firstName":"赖","groups":"","id":"lyj","lastName":"月京","password":"111"},{"email":"123@qq.com","firstName":"沈","groups":"","id":"sjb","lastName":"静斌","password":"111"},{"email":"sds@qq.com","firstName":"sd","groups":"","id":"ss","lastName":"sd","password":"111"},{"email":"123@qq.com","firstName":"史","groups":"","id":"szx","lastName":"珍湘","password":"111"},{"email":"123@qq.com","firstName":"王","groups":"","id":"wangba","lastName":"八","password":"111"},{"email":"123@qq.com","firstName":"系","groups":"","id":"xfdy","lastName":"辅导员","password":"111"},{"email":"123@qq.com","firstName":"学","groups":"","id":"xs","lastName":"生","password":"111"},{"email":"123@qq.com","firstName":"学","groups":"","id":"xsc","lastName":"生处","password":"111"},{"email":"123@qq.com","firstName":"张","groups":"","id":"zhangsan","lastName":"三","password":"111"}]
		Map<String, Object> map = new HashMap<String, Object>();
		List<User> userList = userService.find(map);
		Long total = userService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(userList);
		result.put("list", jsonArray);
		ResponseUtil.write(response, result);
		
	}

	@RequestMapping(value = "/testTimeAjax")
	public void testTimeAjax(HttpServletRequest request, HttpServletResponse response) throws Exception {

		ResponseUtil.write(response, ++PropertityUtil.INDEX);
		
	}
}